const buttonContainer = document.querySelector('.buttons')
const prevElement = document.querySelector('.prev')
const currentElement = document.querySelector('.current')
let currentNumber = '', prevNumber = '', sign = ''


buttonContainer.addEventListener('click', e => {
    const type = e.target.dataset.type
    const text = e.target.textContent
    if (type === 'equal') {
        calculate()
    } else if (type === 'operate') {
        operate(text)
    }
    else if (type === 'delete') {
        deleteFn()
    } else if (type === 'clear') {
        clear()
    } else {
        pushNumber(text)
    }
    updateScreen()
})

function pushNumber(num) {
    currentNumber = currentNumber + num
}
function clear() {
    currentNumber = ''
    prevNumber = ''
    sign = ''
}
function deleteFn() {
    if (!currentNumber.toString().length) return
    currentNumber = currentNumber.toString().slice(0, -1)
}

function operate(text) {
    if (!currentNumber.toString().length) return
    sign = text
    prevNumber = currentNumber
    currentNumber = ''
}

function calculate() {
    if (!prevNumber || !currentNumber || !sign) {

        return;
    }

    let result;
    switch (sign) {
        case '+':
            result = parseFloat(prevNumber) + parseFloat(currentNumber)
            break
        case '-':
            result = parseFloat(prevNumber) - parseFloat(currentNumber)
            break
        case '*':
            result = parseFloat(prevNumber) * parseFloat(currentNumber)
            break
        case '/': 
            if (currentNumber === '0') {
                alert('除数不能为零');
                return
            }
            result = parseFloat(prevNumber) / parseFloat(currentNumber)
            break

        default:

            return
    }

    currentNumber = result.toFixed(2)
    sign = ''
    prevNumber = ''
    updateScreen()
}

function updateScreen() { 
    currentElement.textContent = currentNumber
    if (sign) {
        prevElement.textContent = `${prevNumber} ${sign}`
    } else {
        prevElement.textContent = ''
    }
}